package com.xiaoshuidi.cloud.framework.weixin.config;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.util.CollectionUtils;

import java.util.stream.Collectors;

@AutoConfiguration
@ConditionalOnProperty(prefix = "lease.weixin", value = "enable", matchIfMissing = false)
@EnableConfigurationProperties(WeixinProperties.class)
public class LeaseWeixinAutoConfiguration {

    @Bean
    public WxMaService wxMaService(WeixinProperties properties) {
        WxMaServiceImpl wxMaService = new WxMaServiceImpl();
        if (!CollectionUtils.isEmpty(properties.getMiniapp())) {
            wxMaService.setMultiConfigs(properties.getMiniapp()
                    .stream().collect(Collectors.toMap(WeixinProperties.MiniApp::getAppId,
                            m -> {
                                WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();
                                config.setAppid(m.getAppId());
                                config.setSecret(m.getAppSecret());
                                return config;
                            })));

        }
        return wxMaService;
    }
}
